//
//  AJTTMineController.swift
//  JourneyThroughTime
//
//  Created by iOS-Czz on 2023/11/629.
//

import UIKit
import ProgressHUD
class AJTTMineController: AJTTBaseViewController,UITextFieldDelegate {
    @IBOutlet var tableView: UITableView!
    lazy var viewModel: AJTTMineViewModel = {
        return AJTTMineViewModel()
    }()
    var selectImage:UIImage? = nil
    @IBOutlet var thoughtsTF: UITextField!
    @IBOutlet var bgView: UIView!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.thoughtsTF.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        self.thoughtsTF.delegate = self
        setTab()
        // Do any additional setup after loading the view. DrivingLicenseNumber
    }
    @objc func textFieldDidChange() {
        
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if self.thoughtsTF.text!.isEmpty {
            ProgressHUD.showError("Please enter my thoughts")
            return false
        }
        if self.selectImage == nil {
            ProgressHUD.showError("Please select a picture")
            return false
        }
        saveMyThoughts()
        return true
    }
    func saveMyThoughts(){
        let model = AJTTMineModel()
        model.content = self.thoughtsTF.text!
        model.date = Date().toString(format: "yyyy-MM-dd")
        model.picture = UIImage.saveImageInCache(self.selectImage!)!
        model.isDefault = false
        model.saveToDB()
        UIView.showResultView("My thoughts addition succeed", true)
        let helper = AJTTMineModel.getUsingLKDBHelper()
        helper.delete(with: AJTTMineModel.self, where: "isDefault = true")
        let delay = 1.5 // 2秒
        let dispatchTime = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
            self.thoughtsTF.text = ""
            self.selectImage = nil
            self.loadData()
        }
    }
    @IBAction func tapPicAction(_ sender: Any) {
        showPickImageVC()
    }
    func setTab(){
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register(UINib(nibName: "AJTTMineListCell", bundle: .main), forCellReuseIdentifier: "AJTTMineListCell")
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.bgView.addRoundCorners(topLeftRadius: 15, topRightRadius: 15, bottomLeftRadius: 0, bottomRightRadius: 0, borderWidth: 0, borderColor: .red)
    }
    func loadData(){
        self.viewModel.getPageData() { models in
            self.tableView.reloadData()
        }
    }  
    
}
extension AJTTMineController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:AJTTMineListCell = tableView.dequeueReusableCell(withIdentifier: "AJTTMineListCell") as! AJTTMineListCell
        cell.model = self.viewModel.dataSource[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
}
extension AJTTMineController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func showPickImageVC() {
        let photoPickerViewController:UIImagePickerController = UIImagePickerController()
        photoPickerViewController.sourceType = UIImagePickerController.SourceType.photoLibrary
        photoPickerViewController.delegate = self
        photoPickerViewController.modalPresentationStyle = .fullScreen
        self.present(photoPickerViewController, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        self.selectImage = selectedImage
        picker.dismiss(animated: true) { [self] in
            if self.thoughtsTF.text!.isEmpty {
                ProgressHUD.showError("Please enter my thoughts")
                return
            }
            saveMyThoughts()
        }
    }
}
